package com.potenza.training.reply.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.potenza.training.reply.config.ReadExcelUtil;
import com.potenza.training.reply.controller.SubjectReplyController;
import com.potenza.training.reply.dao.EsDao;
import com.potenza.training.reply.dao.KeyWordDao;
import com.potenza.training.reply.dao.SubjectDao;
import com.potenza.training.reply.entity.*;
import com.potenza.training.reply.feign.SubjectFegin;
import com.potenza.training.reply.service.SubjectService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("subjectService")
public class SubjectServiceImpl extends ServiceImpl<SubjectDao, SubjectEntity> implements SubjectService {
    @Resource
    SubjectDao subjectDao;
    @Resource
    private KeyWordDao keyWordDao;
    @Resource
    SubjectReplyController subjectReplyController;
    @Resource
    SubjectFegin fegin;
    @Autowired
    EsDao esDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SubjectEntity> page = this.page(
                new Query<SubjectEntity>().getPage(params),
                new QueryWrapper<SubjectEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public R saveIkAndSubject(SubjectDTO subjectDTO) {

        //添加提目表
        SubjectEntity subject= new SubjectEntity();
        subject.setTimeLimit(subjectDTO.getTimeLimit());
        subject.setSubjectType(subjectDTO.getSubjectType());
        subject.setSubjectDifficlty(subjectDTO.getSubjectDifficlty());
        subject.setSubiectDesc(subjectDTO.getSubiectDesc());
        subject.setTitleName(subjectDTO.getTitleName());
        subject.setBeginData(new Date());
        subject.setEndData(new Date());
        subject.setStandardAnswer(subjectDTO.getStandardAnswer());//标准答案
        //类型
        //SubjectTypeEntity subjectTypeEntity = JSON.parseObject(subjectDTO.getSubjectType(), SubjectTypeEntity.class);
        subject.setTypeId(subjectDTO.getTypeId());
        //SubjectDifficultyEntity subjectDifficultyEntity = JSON.parseObject(subjectDTO.getSubjectDifficlty(), SubjectDifficultyEntity.class);
        subject.setDifficltyId(subjectDTO.getDifficltyId());



        baseMapper.insert(subject);

        //添加分词表数据
        //1:遍历添加
        System.out.println(subject.getId());
        KeyWordEntity wordEntity = new KeyWordEntity();
        //获取前台传递来的参数
        List<KeyWordEntity> keyWordEntityList = subjectDTO.getKeyWordEntityList();
        String keyword1 = "";
        String groups1="";
        Integer i=0;
        for (KeyWordEntity keyWordEntity : keyWordEntityList) {
            System.out.println(keyWordEntity);
            wordEntity.setTbSubjectId(subject.getId());
            wordEntity.setKeyWordName(keyWordEntity.getKeyWordName());
            List<Cs> cs = JSON.parseArray(keyWordEntity.getKeyWordName(), Cs.class);
            for (Cs c : cs) {
                keyword1+=c.getKeyWordName()+",";
                i++;
            }
            wordEntity.setGroups(keyWordEntity.getGroups());
            groups1+=i+":"+keyWordEntity.getGroups()+",";
            keyWordDao.insert(wordEntity);
        }
        // 将我添加的数据同步到我们es模板表中
        EsSubjectEntity esSubjectEntity = new EsSubjectEntity();
        esSubjectEntity.setId(subject.getId());
        System.out.println(esSubjectEntity.getId()+"------------------------------------------------");
        esSubjectEntity.setSubjectType(subject.getSubjectType());
        esSubjectEntity.setSubjectDifficlty(subject.getSubjectDifficlty());
        esSubjectEntity.setTitleName(subject.getTitleName());
        esSubjectEntity.setStandardAnswer(subject.getStandardAnswer());
        esSubjectEntity.setTimeLimit(subject.getTimeLimit());
        esSubjectEntity.setSubiectDesc(subject.getSubiectDesc());
        esSubjectEntity.setIsStart(1);
        esSubjectEntity.setBeginData(subject.getBeginData());
        esSubjectEntity.setEndData(subject.getEndData());
        esSubjectEntity.setTypeId(subject.getTypeId());
        esSubjectEntity.setDifficltyId(subject.getDifficltyId());
        esSubjectEntity.setKeyWordName(keyword1);
        esSubjectEntity.setGroups(groups1);
        esDao.insert(esSubjectEntity);
        return R.ok();
    }

    @Override
    public Page<SubjectEntity> findAll(Map map,Integer pageNum,Integer pageSize) {
        QueryWrapper<SubjectEntity> subjectEntityQueryWrapper = new QueryWrapper<>();
        String subjectType = (String) map.get("subjectType");
        String subjectDifficlty = (String) map.get("subjectDifficlty");
        String titleName = (String) map.get("titleName");
        List<Long> ids = new ArrayList<>();
        String list = JSON.toJSONString(map.get("defenseList"));
        System.out.println(list);
        if (!StringUtils.isEmpty(subjectType)){
            subjectEntityQueryWrapper.lambda().like(SubjectEntity::getSubjectType,subjectType);
        }
        if (!StringUtils.isEmpty(subjectDifficlty)){
            subjectEntityQueryWrapper.lambda().like(SubjectEntity::getSubjectDifficlty,subjectDifficlty);
        }
        if (!StringUtils.isEmpty(titleName)){
            subjectEntityQueryWrapper.lambda().like(SubjectEntity::getTitleName,titleName);
        }
        List<SubjectEntity> list1 = (List<SubjectEntity>) JSON.parseArray(list,SubjectEntity.class);
        if (!StringUtils.isEmpty(list1)&&list1!=null&&list1.size()!=0){
            for (SubjectEntity subjectEntity : list1) {
                ids.add(subjectEntity.getId());
            }
            subjectEntityQueryWrapper.lambda().notIn(SubjectEntity::getId,ids);
        }
        Page<SubjectEntity> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNum);
        return subjectDao.selectPage(page,subjectEntityQueryWrapper);
    }

    @Override
    public SubjectEntity findById(Long id) {
        return subjectDao.selectById(id);
    }

    //随机生成题目
    @Transactional
    @Override
    public void immediately(Integer id) {
        QueryWrapper<SubjectEntity> wrapper = new QueryWrapper<>();
        wrapper.last("ORDER BY RAND() LIMIT "+10);
        List<SubjectEntity> subjectEntities = subjectDao.selectList(wrapper);
        int ids[] = new int[10];
        for (int i = 0; i < subjectEntities.size(); i++) {
                ids[i] = Math.toIntExact(subjectEntities.get(i).getId());
        }
        subjectReplyController.insert(id,ids);
    }

    @Override
    public R saveSubject(FileInputStream fileInputStream) throws Exception {
        ReadExcelUtil readExcelUtil = new ReadExcelUtil();
        List<Subject> list = readExcelUtil.testReadType(fileInputStream);
        for (Subject subject : list) {
            //获取分类数据
            String subjectType = subject.getSubjectType();
            SubjectTypeEntity subjectTypeEntity = fegin.findAllByName(subjectType);
            //将题目难度加入实体类
            String subjectDifficlty = subject.getSubjectDifficlty();
            Difficulty difficulty = new Difficulty();
            if(subjectDifficlty.equals("初级")){
                difficulty.setId("1");
            }else if(subjectDifficlty.equals("中级")){
                difficulty.setId("2");
            }else{
                difficulty.setId("3");
            }
            difficulty.setDifficultyName(subjectDifficlty);
            difficulty.setPid("0");
            //转为JSON
            String subjecttype = JSON.toJSONString(subjectTypeEntity);
            String subjectDifficulty = JSON.toJSONString(difficulty);
            //加入题目实体类
            SubjectEntity subjectEntity = new SubjectEntity();
            subjectEntity.setTitleName(subject.getTitleName());
            subjectEntity.setSubjectDifficlty(subjectDifficlty);
            subjectEntity.setSubjectType(subjecttype);
            subjectEntity.setBeginData(new Date());
            subjectEntity.setEndData(new Date());
            subjectEntity.setTimeLimit(Integer.parseInt(subject.getTimeLimit()));
            subjectEntity.setSubiectDesc(subject.getSubiectDesc());
            subjectEntity.setIsStart(1);
            subjectEntity.setStandardAnswer(subject.getStandardAnswer());
            System.out.println(subjectEntity);
            //加入到数据库
            baseMapper.insert(subjectEntity);
        }
        return R.ok();
    }
}